package com.softright.net;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * @author lemon
 *
 */
public class FileUpload {

	private static final String BOUNDARY = "---------7d4a6d158c9";

	private static final String END = "--" + FileUpload.getBoundary() + "--\r\n";

	protected static final String getBoundary() {
		return BOUNDARY;
	}

	public String doUpload(String targetURL, MutilPartEntity entity) throws FileUploadException {
		if (targetURL == null || targetURL.length() <= 0 || !targetURL.startsWith("http")) {
			throw new FileUploadException("#doUpload(String targetURL, List<MutilPartBody> bodyList)# targetURL invalid, " + targetURL);
		}
		List<MutilPartBody> bodyList = entity.getBodyList();
		if (bodyList == null || bodyList.size() <= 0) {
			throw new FileUploadException("#doUpload(String targetURL, List<MutilPartBody> bodyList)# bodyList is empty");
		}
		HttpURLConnection conn = null;
		URL url = null;
		StringBuilder returnSb = new StringBuilder();
		try {
			url = new URL(targetURL);
		} catch (MalformedURLException e) {
			throw new FileUploadException(e);
		}
		try {
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
		} catch (IOException e) {
			throw new FileUploadException(e);
		}
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setReadTimeout(50000);
		conn.setConnectTimeout(50000);
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
		try {
			DataOutputStream dataOutputStream = new DataOutputStream(conn.getOutputStream());
			for (int i = 0; i < bodyList.size(); i++) {
				dataOutputStream.writeBytes("--" + FileUpload.getBoundary());
				dataOutputStream.writeBytes("\r\n");
				MutilPartBody body = bodyList.get(i);
				body.put(dataOutputStream);
				if (i != bodyList.size()) {
					dataOutputStream.writeBytes("\r\n");
				}
			}
			dataOutputStream.writeBytes(END);
			dataOutputStream.flush();
			InputStream inputStream = conn.getInputStream();
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				returnSb.append(inputLine);
			}
			dataOutputStream.close();
			in.close();
		} catch (IOException e) {
			throw new FileUploadException(e);
		}
		conn.disconnect();
		return returnSb.toString();
	}

}
